package Util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.mail.*;
import javax.mail.internet.*;
import java.io.InputStream;
import java.util.Properties;

public class EmailSender {
    // 使用 Log4j2 的 Logger
    private static final Logger logger = LogManager.getLogger(EmailSender.class);

    public static void sendEmail(String to, String subject, String body) {
        // 读取配置文件
        Properties configProps = new Properties();
        try (InputStream input = EmailSender.class.getClassLoader().getResourceAsStream("config.properties")) {
            if (input == null) {
                logger.error("无法找到配置文件 config.properties");
                return;
            }
            configProps.load(input);
        } catch (Exception e) {
            logger.error("读取配置文件失败", e);
            throw new RuntimeException("读取配置文件失败", e);
        }

        // 获取邮件服务器配置
        String host = configProps.getProperty("mail.smtp.host");
        // 获取用户名
        final String username = configProps.getProperty("mail.username");
        // 获取授权码
        final String password = configProps.getProperty("mail.password");

        // 设置邮件属性
        Properties props = new Properties();
        // 开启调试模式
        props.put("mail.smtp.auth", configProps.getProperty("mail.smtp.auth"));
        props.put("mail.smtp.starttls.enable", configProps.getProperty("mail.smtp.starttls.enable"));
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", configProps.getProperty("mail.smtp.port"));

        // 获取默认的Session对象
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            Message message = new MimeMessage(session);

            message.setFrom(new InternetAddress(username));

            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

            message.setSubject(subject);

            message.setText(body);

            Transport.send(message);


            logger.info("邮件发送成功!");
            System.out.println("邮件发送成功!");
        } catch (MessagingException e) {
            logger.error("邮件发送失败", e);
            throw new RuntimeException("邮件发送失败", e);
        }
    }
}